package com.mrper.ui.main;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miguo.activity.callback.IGoodsScroll;
import com.miguo.activity.callback.listener.GoodsScrollListener;
import com.miguo.app.AppHelper;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.pulltorefresh.PullToRefreshBase;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.ui.R;
import com.miguo.ui.databinding.FragmentBrandcategoryListcontentBinding;
import com.miguo.ui.databinding.ListitemBrandcategoryBinding;
import com.mrper.ext.adapter.TempleteAdapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.uibase.BasicFragment;
import com.mrper.model.entry.brand.BrandThemeInfoEntry;
import com.mrper.util.AnimationUtil;
import com.mrper.util.DensityUtil;
import com.mrper.util.DeviceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2016/3/10.
 * 品牌数据列表片段
 */
@ContentView(R.layout.fragment_brandcategory_listcontent)
public class FragmentBrandCategoryListContent extends BasicFragment<FragmentBrandcategoryListcontentBinding>
        implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListenerTwo<ListView>, IGoodsScroll, View.OnClickListener {

    public static final String TAG = FragmentBrandCategoryListContent.class.getSimpleName();
    private TempleteAdapter<ListitemBrandcategoryBinding, BrandThemeInfoEntry> adapter;//数据适配器
    private int currentPage = 0, pageCount = 0, lastVisibleItemIndex = 0;//当前页码,上一次可见的列表项索引
    private int categoryType = -1;//分类ID

    @Override
    @SuppressWarnings("unchecked")
    protected void initViews() {
        super.initViews();
        dataBinder.setOnClickEvent(this);
        adapter = new TempleteAdapter(context, R.layout.listitem_brandcategory,
                new TempleteAdapter.OnInitAdapterListener<ListitemBrandcategoryBinding, BrandThemeInfoEntry>() {
                    @Override
                    public void initSetValue(ListitemBrandcategoryBinding binder, BrandThemeInfoEntry item, int position) {
                        ViewGroup.LayoutParams layoutParams = binder.imgTheme.getLayoutParams();
                        layoutParams.width = (int) (DeviceUtil.getScreenWidth(context) - DensityUtil.dip2px(context, 16f));
                        layoutParams.height = (int) (layoutParams.width * 0.40f);
                        binder.imgTheme.setLayoutParams(layoutParams);
                        binder.imgTheme.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        binder.setItem(item);
                    }
                });
        dataBinder.lvBrand.setAdapter(adapter);
        dataBinder.lvBrand.setOnItemClickListener(this);
        dataBinder.lvBrand.setOnRefreshListener(this);
        dataBinder.lvBrand.setOnScrollListener(new GoodsScrollListener(this));
        dataBinder.stateView.setContentView(dataBinder.flCOntainer);
        dataBinder.stateView.getRefreshView().setOnClickListener(this);
        dataBinder.stateView.getNetworkView().setOnClickListener(this);
    }

    @Override
    protected void onActivityLoadFinished() {
        super.onActivityLoadFinished();
        categoryType = getArguments().getInt("category_id", -1);
    }

    @Override
    protected void doDataLoad() {
        super.doDataLoad();
        loadBrandThemes(); //加载品牌数据
    }

    @Override
    protected boolean isInitHttpCallback() {
        return false;
    }

    @Override
    public boolean isInitShowLoadingDialog() {
        return true;
    }

    @Override
    public void onScrollIdle() {
        imageLoader.resume();
    }

    @Override
    public void onScrollFling() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTouchScroll() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTopPositiont() {
        // 判断滚动到顶部
        if (dataBinder.img2Top.getVisibility() == View.VISIBLE) {
            dataBinder.img2Top.setVisibility(View.GONE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2HideAnimation());
        }
    }

    @Override
    public void onScrollFirstLastPosition() {
        onScrollLastPosition();
//         第一次滚动至底部
//        if (dataBinder.img2Top.getVisibility() == View.GONE) {
//            dataBinder.img2Top.setVisibility(View.VISIBLE);
//            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
//        }
    }

    @Override
    public void onScrollLastPosition() {
        // 判断滚动到底部
        if (dataBinder.img2Top.getVisibility() == View.GONE) {
            dataBinder.img2Top.setVisibility(View.VISIBLE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
        }
        if (currentPage + 1 <= pageCount) {
            loadBrandThemes();//加载品牌数据
        } else {
//            Toast.show(context, "已经到底了!");
            dataBinder.lvBrand.onRefreshComplete();
        }
    }

    @Override
    public void onResume() {
        if (adapter != null)//刷新页面数据
            adapter.notifyDataSetChanged();
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl://刷新事件
            case R.id.network_error_ll://网络错误事件
                loadBrandThemes();//加载商品数据
                break;
            case R.id.img2Top://去顶部
                dataBinder.lvBrand.setSection(0);
                onScrollTopPositiont();//执行滚动到顶部隐藏的动画
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AppHelper.startBrandDetailListPage(activity, (BrandThemeInfoEntry) adapter.getItem(position - 1));
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        currentPage = 0;//页码默认为0
        loadBrandThemes();//加载商品数据
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (currentPage + 1 > pageCount) {
            Toast.show(context, "已经到底了!");
            dataBinder.lvBrand.onRefreshComplete();
            return;
        }
        loadBrandThemes();//加载商品数据
    }

    /**
     * 加载品牌数据
     **/
    private void loadBrandThemes() {
        //加载品牌数据
        Map<String, String> params = new HashMap<>();
        params.put("classify", String.valueOf(categoryType));
        params.put("page", String.valueOf(++currentPage));
        if (httpCallback == null) initHttpCall(); //初始化回调对象
        HttpClient.post(Url.toRoute(Url.ExtUrl.BrandThemeList, 1), params, httpCallback);
    }

    @Override
    public void onLoadHttpDataSuccessful(JsonData json) {
        super.onLoadHttpDataSuccessful(json);
        dataBinder.lvBrand.onRefreshComplete();
        if (json.optInt("status") == 200) {
            JsonData json_data = json.optJson("data");
            try {
                JsonData json_page = json_data.optJson("page");
                currentPage = json_page.optInt("page");
                pageCount = json_page.optInt("page_size");
                //设置页面数据
                List<BrandThemeInfoEntry> themes = new Gson().fromJson(
                        json_data.optJson("brand").toString(),
                        new TypeToken<ArrayList<BrandThemeInfoEntry>>() {
                        }.getType()
                );
                if (themes != null && themes.size() > 0) {
                    if (currentPage == 1) {//重置加载，清空数据
                        adapter.clear();
                    }
                    adapter.addItem(themes);
                    adapter.syncDataSource();
                }
                dataBinder.stateView.setRefreshVisibility(View.GONE);
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
            currentPage--;
            Toast.show(context, getResources().getString(R.string.pull_to_refresh_nodata));
        } else {
            currentPage--;
            Toast.show(context, json.optString("info"));
        }
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onLoadHttpDataFaield(FailData data) {
        super.onLoadHttpDataFaield(data);
        dataBinder.lvBrand.onRefreshComplete();
        if (currentPage > 0) currentPage--; //页码最小不能小于0，大于0的情况下，如果未加载成功，页面需要还原
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

}
